/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.security.authenticate;

import java.util.Collection;
import java.util.HashMap;

import org.geoscheduler.exceptions.GSAuthenticationException;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Account.AccountType;

/**
 * Provider of {@link Authenticator}s.
 * 
 * After initializing (eg. registering all available authenticators) it provides
 * authenticators according to requested {@link AccountType}.
 *
 * @author srakyi
 */
public class AuthenticatorProvider {

	private HashMap<AccountType, Authenticator> auths = new HashMap<AccountType, Authenticator>(2);
	
	public AuthenticatorProvider(Collection<Authenticator> auths) {
		for (Authenticator a : auths) {
			this.auths.put(a.getApplicableTo(), a);
		}
	}
	
	/**
	 * Returns {@link Authenticator} for given {@link AccountType}.
	 * 
	 * @param atype	{@link AccountType} to find {@link Authenticator} for.
	 * 
	 * @return	Instance of {@link Authenticator} interface capable of checking given type of account.
	 */
	public Authenticator getAuthForType(AccountType atype) {
		return this.auths.get(atype);
	}
	
	public boolean checkCredentials(Account a) throws GSAuthenticationException {
		if (a == null) {
			throw new NullPointerException("Null account not expected!");
		}
		
		Authenticator auth = this.auths.get(a.getAccountTypeEnum());
		if (auth == null) {
			// FIXME [srakyi] localize me!
			throw new GSAuthenticationException("Authenticator for given account type not registered!");
		} else {
			return auth.checkCredentials(a);
		}
	}
}
